package com.education.cloud.util.config;

import com.google.common.net.HttpHeaders;
import com.education.cloud.util.constant.Constants;
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.util.Base64Utils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Description 服务间调用携带Authorization请求头
 * @Date 2020/3/22
 * @Created by 67068
 */
public class CustomFeignConfig {


    @Bean
    public RequestInterceptor oauth2FeignRequestInterceptor() {
        return requestTemplate -> {
            // 请求头中添加 Gateway Token
            String zuulToken = new String(Base64Utils.encode(Constants.GATEWAY_TOKEN_VALUE.getBytes()));
            requestTemplate.header(Constants.GATEWAY_TOKEN_HEADER, zuulToken);
            HttpServletRequest request = getHttpServletRequest();
            if (request != null) {
                requestTemplate.header(Constants.TOKEN, getHeaders(request).get(Constants.TOKEN));
            }
        };
    }

    private HttpServletRequest getHttpServletRequest() {
        try {
            // hystrix隔离策略会导致RequestContextHolder.getRequestAttributes()返回null
            // 解决方案：http://www.itmuch.com/spring-cloud-sum/hystrix-threadlocal/
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null)
                return attributes.getRequest();
            return null;
        } catch (Exception e) {
            return null;
        }
    }

    private Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }


}
